const { result, ruleset } = require("@hapi/joi/lib/base");
const db = require("../../db/index");
const { get } = require("../artcate");
// 获取分类列表
const getArtiCates = (req, res) => {
  const sql = `select * from  en_article_cate where is_delete=0 order by id asc`;
  db.query(sql, (err, result) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "获取分类列表成功",
      data: result,
    });
  });
};
// 添加用户列表
const addArticleCates = (req, res) => {
  const sql1 = `select * from en_article_cate where name=? or alias=?`;
  db.query(sql1, [req.body.name, req.body.alias], (err, result) => {
    if (err) return res.cc(err);
    if (result.length === 2) return res.cc("分类名称与别名被占用,请更换后重试");
    if (result.length === 1 && result[0].name === req.body.name)
      return res.cc("分类名称被占用,请更换重试");
    if (result.length === 1 && result[0].alias === req.body.alias)
      return res.cc("分类别名被占用,请更换后重试");
  });
  const sql2 = `insert into en_article_cate set ?`;
  db.query(sql2, req.body, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("更新文章分类失败");
    res.cc("新增文章分类成功!", 0);
  });
};
// 删除文章分类
const deleteCateById = (req, res) => {
  const sql = "update en_article_cate set is_delete=1 where id=?";
  db.query(sql, req.params.id, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("删除文章分类失败");
    res.cc("删除文章分类成功", 0);
  });
};
// 根据id获取文章分类
const getArticleById = (req, res) => {
  const sql = `select * from en_article_cate where id=?`;
  db.query(sql, req.params.id, (err, result) => {
    if (err) return res.cc(err);
    if (result.length !== 1) return res.cc("获取文章分类数据失败");
    res.send({
      status: 0,
      message: "获取文章分类数据成功",
      data: result[0],
    });
  });
};
// 更新文章分类的处理函数
const updateCateById = (req, res) => {
  const sql1 = `select * from en_article_cate where Id<>? and (name=? or alias=?)`;
  db.query(
    sql1,
    [req.body.Id, req.body.name, req.body.alias],
    (err, result) => {
      if (err) return res.cc(err);
      if (result.length === 2)
        return res.cc("分类名称与别名被占用,请更换后重试");
      if (result.length === 1 && result[0].name === req.body.name)
        return res.cc("分类名称被占用,请更换重试");
      if (result.length === 1 && result[0].alias === req.body.alias)
        return res.cc("分类别名被占用,请更换重试");
    }
  );
  const sql2 = `update en_article_cate set ? where Id=?`;
  db.query(sql2, [req.body, req.body.Id], (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("更新文章分类失败");
    res.cc("更新文章分类成功", 0);
  });
};
module.exports = {
  getArtiCates: getArtiCates,
  addArticleCates: addArticleCates,
  deleteCateById: deleteCateById,
  getArticleById: getArticleById,
  updateCateById: updateCateById,
};
